package com.sprite.framework.entity.bridge;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;

import com.sprite.utils.UtilBeans;
import com.sprite.utils.conversion.ConversionException;
import com.sprite.utils.conversion.Converts;

/**
 * 将行数据映射成对象
 * <p>如果查询结果只包含一个列值，支持转换成String、Number</p>
 * @param <T>
 * @author Jack
 */
public class RowToObjectMapper<T> implements RowMapper<T>{

	private Class<T> clazz ;
	
	public RowToObjectMapper(Class<T> clazz) {
		this.clazz = clazz;
	}
	
	@Override
	public T mapRow(ResultSet rs, int rowNum) throws SQLException {
	
		try {
			int colCount = rs.getMetaData().getColumnCount();
			
			if(!UtilBeans.isBean(clazz) && colCount == 1) {// 查询结果仅有一个，可转为String、Number
				return Converts.convert(rs.getObject(colCount), clazz);
			}
			
			T obj = UtilBeans.instance(clazz);
			Object value = null;
			for(; colCount>0; colCount--) {
				value = rs.getObject(colCount);
				if(value == null) {
					continue;
				}
				UtilBeans.setProperty(obj, rs.getMetaData().getColumnLabel(colCount), value);
			}
			
			return obj;
		} catch (InstantiationException | IllegalAccessException e) {
			throw new SQLException(e);
		} catch (ConversionException e) {
			throw new SQLException(e);
		}
	}

}
